<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * @brief 准备数据库连接
 * @param none
 * @return 创建成功后返回已创建好的数据库连接，遇到错误时返回失败信息
 */
function prepare()
{
    $serverName = ".";
    $connectionInfo = array("Database"=>"BookStore", 'ReturnDatesAsStrings'=> true, "CharacterSet" => 'utf-8');
    
    $conn = sqlsrv_connect($serverName, $connectionInfo);

    if($conn){//连接数据库成功
        //echo "Connection established.\n";
    }else{//连接数据库失败
        echo "Connection could not be established.\n";
        die(print_r( sqlsrv_errors(), true));
        
        return false;//返回失败信息
    }
    
    return $conn;//返回连接
}

/**
 * @brief 执行SQL语句，完成对数据库的CRUD操作
 * @param in $conn 已创建的数据库连接
 * @param in $statement 准备好的SQL语句
 * @return 正常执行时返回执行SQL语句后的结果，遇到错误时返回失败信息
 */
function exectue_sql_statement($conn ,$statement) 
{
    $stmt = sqlsrv_query($conn, $statement);
    
    if($stmt === false){//执行SQL语句失败
        echo "Statement could not be executed.\n";
        die(print_r( sqlsrv_errors(), true));
        
        return false;//返回失败信息
    }
    
    /*
    //select row
    if( sqlsrv_fetch( $stmt ) === false){
         echo "Error in retrieving row.\n";
         die( print_r( sqlsrv_errors(), true));
    }
    echo sqlsrv_get_field( $stmt, 0);
    echo sqlsrv_get_field( $stmt, 1);
    sqlsrv_fetch( $stmt,SQLSRV_SCROLL_NEXT );
    */
    
    return $stmt;//返回执行结果
}

/**
 * @brief 释放数据库连接
 * @param in $stmt 执行SQL语句后返回的执行结果
 * @return none
 * @remark 在本系统中并未调用本函数
 */
function free($stmt)
{
    sqlsrv_free_stmt($stmt);
}

/**
 * @brief 关闭数据库连接
 * @param in $conn 已创建的数据库连接
 * @return none
 * @remark 在本系统中并未调用本函数
 */
function close($conn)
{
    sqlsrv_close($conn);
}

/* 
//datetime
$stmt = sqlsrv_query( $conn, "select orders_date from Orders");
if( $stmt === false ){
    echo "Statement could not be executed.\n";
    die( print_r( sqlsrv_errors(), true));
}
sqlsrv_fetch( $stmt );
$date = sqlsrv_get_field( $stmt, 0);
if( $date === false ) {
   die( print_r( sqlsrv_errors(), true ));
}
echo $date;
*/
?>
